package com.ios.service.impl;

import com.ios.dao.CallLogMapper;
import com.ios.dao.DisablerUserMapper;
import com.ios.dao.RelativeUserMapper;
import com.ios.dto.CallLogExecution;
import com.ios.entity.CallLog;
import com.ios.entity.DisablerUser;
import com.ios.entity.RelativeUser;
import com.ios.enums.CallLogEnum;
import com.ios.service.ICallLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CallLogServiceImpl implements ICallLogService {
    @Autowired
    private CallLogMapper callLogMapper;
    @Autowired
    private DisablerUserMapper disablerUserMapper;
    @Autowired
    private RelativeUserMapper relativeUserMapper;

    @Override
    public CallLogExecution CreateCall(int disabler_id) {
        if (disabler_id == -1){
            return new CallLogExecution(CallLogEnum.NULL_PARAM);
        }else if (!CheckDisablerId(disabler_id)){
            return new CallLogExecution(CallLogEnum.NULL_USER);
        }else {
            try{
                CallLog callLog = new CallLog();
                DisablerUser disablerUser = disablerUserMapper.selectByPrimaryKey(disabler_id);
                RelativeUser relativeUser = relativeUserMapper.queryByDisabler(disabler_id);
                if (disablerUser.getFirstContact().equals(null)){
                    callLog.setCreateTime(new Date());
                    callLog.setUpdateTime(new Date());
                    callLog.setDisablerId(disabler_id);
                    callLog.setRelativeId(relativeUser.getId());
                    callLogMapper.insert(callLog);
                    if (!relativeUser.getPhoneNo().equals(null)){
                            return new CallLogExecution(CallLogEnum.CALL_SUCCESS_RELATIVE,relativeUser.getPhoneNo());
                    }else {
                        return new CallLogExecution(CallLogEnum.CALL_FAIL_RELATIVE);
                    }
                }else {
                    callLog.setCreateTime(new Date());
                    callLog.setUpdateTime(new Date());
                    callLog.setDisablerId(disabler_id);
                    callLog.setRelativeId(relativeUser.getId());
                    callLogMapper.insert(callLog);
                    return new CallLogExecution(CallLogEnum.CALL_SUCCESS,disablerUser.getFirstContact());
                }
            }catch (Exception e){
                return new CallLogExecution(CallLogEnum.CALL_FAIL);
            }
        }
    }

    /*判断用户是否存在*/
    private boolean CheckDisablerId(Integer disablerId){
        List<Integer > AllId = disablerUserMapper.getAllDisablerId();
        for (Integer id : AllId){
            if (id==disablerId){
                return true;
            }
        }
        return false;
    }
}
